package edu.nuist.app.controller.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWTUtil;
import edu.nuist.app.controller.service.LoginService;
import edu.nuist.app.entity.LoginUser;
import edu.nuist.app.entity.User;
import edu.nuist.app.enums.CustomExceptionType;
import edu.nuist.app.response.AjaxResponse;
import edu.nuist.app.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangzhuangzhuang
 * @DESC:
 * @date 2022-04-03 21:29
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

	@Autowired
	private AuthenticationManager authenticationManager;

	@Autowired
	private UserDetailsService userDetailsService;

	@Autowired
	private JwtUtil jwtUtil;

	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public AjaxResponse login(User user) {
		// AuthenticationManager authenticate进行用户认证
		UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
				new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
		Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
		log.info("[LoginServiceImpl][login]authenticate: {}", authenticate);
		// 如果认证没有通过则给出对应的提示
		if(ObjectUtil.isNull(authenticate)){
			return AjaxResponse.error(CustomExceptionType.USER_INPUT_ERROR, "登录失败!");
		}
		// 如果认证通过了，使用userid生成一个jwt 存入ResponseResult返回
		UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUserName());
		String token = jwtUtil.generateToken(userDetails);
		// 把完整的用户信息存入Redis userid作为key
		LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
		HashMap<String, String> userInfoMap = new HashMap<>();
		redisTemplate.boundValueOps("login" + loginUser.getUser().getId()).set(loginUser);
		return AjaxResponse.success(token, "登录成功!");
	}
}